@{
    ViewData["Titel"] = "备份";
}

@*
    <!DOCTYPE html>*@


@*<head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
    </head>*@
<h2 style="margin:20px 0">全库操作</h2>
<hr />
<form method="post" enctype="multipart/form-data" asp-controller="InfoLog" asp-action="FileRecover">

    <input type="hidden" id="yz" value="" />
    <div>



        <div class="row">
            <input type="button" id="btnBackUpAll" class="  btn btn-default " value="备份全库" />
            <span class=" btn btn-default " style="position: relative;
        display: inline-block;
        overflow: hidden;cursor:pointer">
                <span style="cursor:pointer">上传全库</span>
                <input type="file" name="fileRecoverAll" id="fileRecoverAll" style="position:absolute;
                right: 0px;
                top: 0px;
                opacity: 0;cursor:pointer;
                -ms-filter: 'alpha(opacity=0)';
                font-size: 200px;">
            </span>
            <div id="btnRecoverAll" class="btn btn-default">恢复全库</div>
        </div>
        <dl id="infoDiv" class="dl-horizontal" style="display: none;cursor: pointer;margin-top:40px;margin-left:-20px;"></dl>
        <div id="href" class="btn btn-default" style="width:140px;margin-left: 40px;margin-top: 40px;" onclick="(()=>{location.href='/InfoLog/index'})()">返回日志列表</div>
    </div>
</form>
<script src="~/lib/jquery/jquery-1.12.4.js"></script>
<script src="~/js/dateformat.js"></script>
<script src="~/Content/layui/layui.js"></script>

<script src="~/js/utils.js"></script>
<script>
    //Base64编码
    function Base64() {
        // private property
        _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        // public method for encoding
        this.encode = function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                    _keyStr.charAt(enc1) +
                    _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) +
                    _keyStr.charAt(enc4);
            }
            return output;
        };

        // public method for decoding
        this.decode = function (input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        };

        // private method for UTF-8 encoding
        _utf8_encode = function (string) {
            string = string.toString().replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }
            return utftext;
        };

        // private method for UTF-8 decoding
        _utf8_decode = function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;
            while (i < utftext.length) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        };
    }

    //外部加密
    function ExternalEncrypt(Json, funcBack) {
        console.log(Json)
        var socket = new WebSocket("ws://127.0.0.1:2012/CustomizeEnvelope");
        try {

            socket.onopen = function (msg) {
                socket.send(Json);
            };
            socket.onmessage = function (e) {
                console.log(e.data, "加密");
                funcBack(e.data);
                socket.close();
            };
        } catch (ex) {
            funcBack("");
            socket.close();
        }

    }

    function EncryptCertList(back) {
        var socket = new WebSocket("ws://127.0.0.1:2012/EncryptCertList");
        try {

            socket.onopen = function (msg) {
                socket.send("1");
            };
            socket.onmessage = function (e) {
                back(e.data);
                socket.close();
            };
        } catch (ex) {
            funcBack("");
            socket.close();
        }
    }

    function myPost(url) {
        var body = $(document.body),
            form = $("<form method='post'></form>"),
            input;
        console.log(1);
        form.attr({
            "action": url
        });
        //$.each(args, function (key, value) {
        //    input = $("<input type='hidden'>");
        //    input.attr({ "name": key });
        //    input.val(value);
        //    form.append(input);
        //});

        form.appendTo(document.body);
        form.submit();
        document.body.removeChild(form[0]);
    }

    function _arrayBufferToBase64(buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }
    function DisplayMessage(message) {
        var mydate = new Date();
        $("#infoDiv").append("<dt>" +
            mydate.Format("hh:mm:ss") +
            "</dt><dd>" +
            message +
            "</dd>");
    }
    $(function () {
        var base64 = new Base64();
        $.ajax({
            url: "/InfoLog/ReturnValidateCode",
            type: 'get',

            success: function (data) {
                $("#yz").val(data.validateCode);
            },
        });
        $('#btnBackUpAll').click(function () {
            myPost("/InfoLog/BackUpAll");
        });
        $('#btnRecoverAll').click(function () {
            var fileObj = document.getElementById("fileRecoverAll").files[0]; // js 获取文件对象
            if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
                layer.msg("请选择文件");
                return;
            }
            var t = fileObj.name.lastIndexOf(".");
            var fileName = fileObj.name.substring("0", t);
            var fileSuffix = fileObj.name.substring(t + 1);
            if (fileSuffix != "db") {
                layer.msg("请上传正确的文件");
                return;
            }
            $("#infoDiv").show();
            console.log(fileName + '.' + fileSuffix + '\n' + fileObj.name);
            // var formFile = new FormData();
            // formFile.append("file", fileObj);
            var reader = new FileReader();
            // var fileBase64 = null;
            reader.onload = function (e) {
                DisplayMessage("正在恢复数据库...");
                var str = reader.result;
                var t = str.indexOf(",");
                str = str.substring(t + 1);
                console.log(str);
                EncryptCertList((data) => {
                    data = JSON.parse(data);
                    let CertID = getCookie("CertID");
                    var dataPost = {
                        fileContent: str,
                        fileName: fileName,
                        fileSuffix: fileSuffix,

                        ValidateCode: $("#yz").val()
                    }
                    console.log(dataPost)
                    var External = {
                        CertID: CertID,
                        //编码
                        DataBase64: base64.encode(JSON.stringify(dataPost))
                    };
                    ExternalEncrypt(JSON.stringify(External), (data) => {
                        data = JSON.parse(data);
                        console.log(data.contentBase64, "222")
                        if (data.error == "Ok") {
                            var data1 = {
                                // ArrayNo: CertID,
                                EncryptData: data.contentBase64
                            };
                            $.ajax({
                                url: "/InfoLog/FileRecoverAll",
                                data: data1,
                                type: "Post",
                                dataType: "json",
                                // cache: false, //上传文件无需缓存
                                // processData: false, //用于对data参数进行序列化处理 这里必须false
                                // contentType: false, //必须
                                success: function (result) {
                                    if (result.state == '200') {
                                        window.location.href = '/InfoLog/Index';
                                        layer.msg(result.message);
                                    } else {
                                        layer.msg(result.message);
                                    }
                                },
                            })



                        }
                    });
                })
            }
            reader.readAsDataURL(fileObj);


        });
    });
</script>
<script>
    $(function () {
        $(document).ready(function () {
            //ajax请求后台数据
            getUserList(10, 1);

        });
        var currentPage = 1;
        //数据请求
        function getUserList(PageSize, PageIndex) {
            $.ajax({
                url: "/InfoLog/Index",
                type: 'POST',
                data: {
                    PageSize,
                    PageIndex
                },
                success: function (result) {
                    console.log(result);
                    var Items = result.data;
                    var total = result.total;
                    console.log(total);
                    showData(Items);
                    pages(total);
                }
            });
        }
        // 展示数据
        function showData(Items) {
            var _html = '';
            console.log(Items);
            $.each(Items, function (i) {
                var Item = Items[i];
                _html += ' <tr class="text-center">';
                _html += '<td>' + Item.userName + '</td >';
                _html += '<td>' + Item.userType + '</td >';
                _html += '<td>' + Item.manageType + '</td >';
                _html += '<td>' + Item.createDate + '</td >';
                _html += '<td>' + Item.remark + '</td >';

            })
            $("#userList").html(_html);

        }
        // 分页条
        function pages(allNum) {
            layui.use(['laypage', 'layer'], function () {
                var laypage = layui.laypage,
                    layer = layui.layer;
                laypage.render({
                    elem: 'Page',
                    count: allNum //数据总数，从服务端得到
                    ,
                    curr: currentPage,
                    theme: '#393D49',
                    jump: function (obj, first) {
                        currentPage = obj.curr;
                        //首次不执行
                        if (!first) {
                            getUserList(10, obj.curr)
                        }
                    }
                });
            })
        };
    })
</script>
